package main

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"time"

	"github.com/Equanox/gotron"
	"github.com/go-vgo/robotgo"
)

var basData []Bas
var restart = make(chan bool)

func main() {
	// Create a new browser window instance
	window, err := gotron.New("./ba_web/build")
	if err != nil {
		panic(err)
	}

	// Alter default window size and window title.
	window.WindowOptions.Width = 600
	window.WindowOptions.Height = 600
	window.WindowOptions.Title = "按键助手"

	window.On(&gotron.Event{Event: "updateBas"}, func(bin []byte) {
		fmt.Println(string(bin))
		var updateBasData UpdateBasData
		err := json.Unmarshal(bin, &updateBasData)
		if err != nil {
			window.Send(&CustomEvent{
				Event: &gotron.Event{Event: "updateBasRes"},
				Data:  err.Error(),
			})
		} else {
			basData = updateBasData.Bas
			restart <- true
		}
	})

	go checkBas()

	// Start the browser window.
	// This will establish a golang <=> nodejs bridge using websockets,
	// to control ElectronBrowserWindow with our window object.
	done, err := window.Start()
	if err != nil {
		panic(err)
	}

	// Open dev tools must be used after window.Start
	// window.OpenDevTools()

	// Wait for the application to close
	<-done
}

type CustomEvent struct {
	*gotron.Event
	Data string `json:"data"`
}

type UpdateBasData struct {
	*gotron.Event
	Bas []Bas `json:"bas"`
}

type Bas struct {
	Name     string `json:"name"`
	Key      string `json:"key"`
	Interval string `json:"interval"`
	Started  bool   `json:"started"`
}

func checkBas() {
	go func() {
		for {
			select {
			case <-restart:
				time.Sleep(3 * time.Second)
			default:
				n := rand.Intn(500) + 500
				time.Sleep(time.Duration(n) * time.Millisecond)

				for _, v := range basData {
					if v.Started {
						if v.Key == "left" || v.Key == "right" {
							fmt.Println("mouse click " + v.Key)
							robotgo.MouseClick(v.Key, true)
						} else {
							fmt.Println("KeyTap " + v.Key)
							robotgo.KeyTap(v.Key)
						}
					}
				}
			}
		}
	}()
}
